package gov.kqqzyyy.monkey.pharmacyscreen.code.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.widget.ListView;
import android.widget.TextView;

import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;
import com.socks.library.KLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.pharmacyscreen.R;
import gov.kqqzyyy.monkey.pharmacyscreen.code.adapter.MyJKCKAdapter;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.CurrentVersion;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.PharmacyWindowBaseActivity;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.SpeakTool;
import gov.kqqzyyy.monkey.pharmacyscreen.code.object.HJBR;

//西药房叫号屏
@SuppressLint("NonConstantResourceId")
public class WMJHScreenActivity extends PharmacyWindowBaseActivity {

    @BindView(R.id.wmjh_window_text)
    TextView mWindowText;
    @BindView(R.id.wmjh_datetime_text)
    TextView mTimeText;
    @BindView(R.id.wmjh_version_text)
    TextView mVersionText;
    @BindView(R.id.wmjh_window_listview)
    ListView mWindowList;

    private MyHandler handler;
    private CallThread callThread;

    private List<HJBR> callList;

    private MyJKCKAdapter mHJBRAdapter;

    private CountDownTimer lagCountTimer;

    private SpeakTool speakTool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wmjhscreen);
        ButterKnife.bind(this);
        onBindUI();
        handler = new MyHandler(this);

        speakTool = new SpeakTool(this);

        mHJBRAdapter = new MyJKCKAdapter(this);
        mWindowList.setAdapter(mHJBRAdapter);
    }

    @Override
    protected void onBindUI() {
        super.onBindUI();
        setTimeTextView(mTimeText);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String mWindowName = getmSharedPreferences().getString("window_name", "");
        mWindowText.setText(mWindowName);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopCallThread();
        if (lagCountTimer != null) {
            lagCountTimer.cancel();
        }
        if (speakTool != null) {
            speakTool.destory();
        }
    }

    private void stopCallThread() {
        if (callThread != null && callThread.isAlive()) {
            callThread.interrupt();
            callThread = null;
        }
    }

    @Override
    public void doFlushData() {
        super.doFlushData();
        doGetHJBR();
    }

    @Override
    public void doSetVersion() {
        super.doSetVersion();
        String text = "版本号：" + CurrentVersion.getVerName(this);
        mVersionText.setText(text);
    }

    @Override
    protected void doFilterData() {
        super.doFilterData();
        boolean isLag = false;
        List<HJBR> hjbrList = getmHJBRList();
        if (hjbrList == null || hjbrList.size() == 0) {
            isLag = true;
        } else {
            callList = new ArrayList<>();
            for (HJBR patient : hjbrList
                    ) {
                if (patient.getJhbz() == 0) {
                    callList.add(patient);
                }
            }
            if (callList.size() > 0) {
                Collections.sort(callList, (arg0, arg1) -> arg0.getWcsj().compareTo(arg1.getWcsj()));
                mHJBRAdapter.setList(callList);
                doCallPatients();
            } else {
                isLag = true;
            }
        }
        if (isLag) {
            lagCountTimer = new CountDownTimer(5000, 2500) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    doFlushData();
                }
            }.start();

        }
    }

    //呼叫病人操作
    protected void doCallPatients() {
        stopCallThread();
        callThread = new CallThread();
        callThread.start();
    }

    //呼叫病人线程
    private class CallThread extends Thread {

        private boolean keepCalling = true;
        private int index = 0;
        private boolean callNext = true;

        @Override
        public void run() {
            super.run();
            while (keepCalling) {
                if (callNext) {
                    callNext = false;
                    HJBR patient = callList.get(index);
                    //名字改颜色
                    Message message = new Message();
                    message.what = 0x29;
                    message.arg1 = patient.getPdhm();
                    message.arg2 = callList.indexOf(patient);
                    handler.sendMessage(message);
                    //语音
                    String speakMessage = "请 " + patient.getPdhm() + " 号 " + patient.getBrxm() + " 到 " + patient.getCkmc() + " 取药 ";
                    speakMessage += " " + speakMessage;
                    speakTool.speak(speakMessage, listener);
                    //更新标记
                    doUpdateXYJHPB(patient);
                }
                try {
//                    Thread.sleep(1000);
                    SystemClock.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private final SynthesizerListener listener = new SynthesizerListener() {
            @Override
            public void onSpeakBegin() {
            }

            @Override
            public void onBufferProgress(int percent, int beginPos, int endPos, String info) {

            }

            @Override
            public void onSpeakPaused() {
            }

            @Override
            public void onSpeakResumed() {
            }

            @Override
            public void onSpeakProgress(int percent, int beginPos, int endPos) {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                KLog.d("APE", index);
                if (index == callList.size() - 1) {
                    keepCalling = false;
                    callNext = false;
                    Message message = new Message();
                    message.what = 0x29;
                    message.arg1 = -1;
                    message.arg2 = -1;
                    handler.sendMessage(message);
                    doFlushData();
                } else {
                    index++;
                    callNext = true;
                }
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
            }
        };

    }

    private static class MyHandler extends Handler {

        WeakReference<WMJHScreenActivity> mActivity;

        MyHandler(WMJHScreenActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            WMJHScreenActivity activity = mActivity.get();
            if (msg.what == 0x29) {
                int pdhm = msg.arg1;
                int position = msg.arg2;
                activity.mHJBRAdapter.setPDHM(pdhm);
                if (position != -1) {
                    activity.mWindowList.smoothScrollToPosition(position);
                    activity.mWindowList.setSelection(position);
                } else {
                    activity.stopCallThread();
                }
            }
        }
    }
}
